<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Weixin_wshop_module extends CI_Module
{
    private $data;
    private $sid;
    private $site_shop_count;

    public function __construct()
    {
        parent::__construct();
        $this->sid = $GLOBALS['sid'];
        $this->site_shop_count = !empty($GLOBALS['config']['site_shop_count'])?$GLOBALS['config']['site_shop_count']:10;
        $this->load->model('admin.Upload_model');
        $this->load->model('weixin.Shop_model');
    }

    /**
     * 微店列表
     *
     *
     */

    public function shop_list()
    {

        $u = $this->db->dbprefix('user');
        $s = $this->db->dbprefix('user_shop_info');
        $condition['word'] = addslashes($this->input->get_post('word'));
        $condition['status'] = addslashes($this->input->get_post('status'));
        $where  = " "  ;
        $status_query = " $s.shop_status <> -1" ;
        if($condition['status']){
            $status_query = " $s.shop_status = 0";
        }
        $where .= $status_query ;
        if($condition['word']){
            $where.= " AND ( $u.mobile LIKE '%".$condition['word']."%' OR $s.company LIKE '%".$condition['word']."%' OR $s.shop_name LIKE '%".$condition['word']."%')";
        }
        $page_config['perpage']=20;   //每页条数
        $page_config['part']=2;//当前页前后链接数量
        $page_config['url']='weixin/wshop/shop_list';//url
        $page_config['param'] = '?word='.$condition['word'] ;//参数
        $page_config['seg']=4;//参数取 index.php之后的段数，默认为3，即index.php/control/function/18 这种形式
        $page_config['nowindex']=$this->uri->segment($page_config['seg']) ? $this->uri->segment($page_config['seg']):1;//当前页
        $page_config['total'] = $this->Shop_model->get_shop_count($where);
        $this->load->library('mypageclass');
        $this->mypageclass->initialize($page_config);
        $this->data['show_add_button'] = FALSE;
        if(($this->Shop_model->get_shop_count())<=$this->site_shop_count)
        {
            $this->data['show_add_button'] = TRUE;
        }
        $this->data['shop_array'] = $this->Shop_model->get_shop_list($where,$page_config['perpage'],$page_config['nowindex']);
        $this->data['form_url'] = site_url('weixin/wshop/shop_list');
        $this->data['condition'] = $condition;
        $this->load->view('/xenon/wshop_list',$this->data);
    }

    /**
     * 添加微店
     *
     *
     */

    public function add_shop()
    {
        if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
        {

            if($this->Shop_model->get_shop_count()>=$GLOBALS['config']['site_shop_count'])
            {
                $this->error('本站点微店数量达到限制,不允许继续添加',site_url('weixin/wshop/shop_list'),true);
            }
            $form_data = $this->input->post('Form');
            $expand_data = $this->input->post('Expand');
            $shop_data = $this->input->post('Shop');
            $mix = $this->Shop_model->_rand_6_char();
            $password = md5(md5($form_data['password'].$mix));
            $login_date = $reg_date = date('Y-m-d H:i:s');
            $login_ip = $reg_ip = $this->input->ip_address();
            $shop_status = !$shop_data['shop_status']?-1:1 ;
            $base_array = array(
                'sid'=>$this->sid ,
                'mobile'=>$form_data['mobile'] ,
                'password'=>$password ,
                'login_date'=>$login_date ,
                'reg_date'=>$reg_date ,
                'login_ip'=>$login_ip ,
                'reg_ip'=>$reg_ip ,
                'status'=>'1' ,
                'mix'=>$mix
            );

            $user_id = $this->Shop_model->_add_shop_user($base_array) ;
            if($user_id)
            {
                $expand_array = array(
                    'sid'=>$this->sid ,
                    'user_id'=>$user_id,
                    'realname'=>$expand_data['realname'],
                    'gender'=>$expand_data['gender'],
                );
                $res = $this->Shop_model->_add_shop_expand($expand_array) ;
                if($res)
                {
                    $shop_array = array(
                        'sid'=>$this->sid,
                        'pid'=>$user_id,
                        'shop_status'=>$shop_status,
                        'shop_name'=>$shop_data['shop_name'],
                        'company'=>$shop_data['company'],
                        'alipay'=>$shop_data['alipay'],
                        'qq'=>$shop_data['qq'],
                        'address'=>$shop_data['address']
                    );
                    $result = $this->Shop_model->_add_shop_info($shop_array) ;
                    if($result)
                    {
                        $this->success('操作成功',site_url('weixin/wshop/shop_list'),true);
                    }
                    $this->error('操作失败',site_url('weixin/wshop/add_shop'),true);
                }
            }
        }
        $this->data['show_add_button'] = FALSE;
        if(($this->Shop_model->get_shop_count())<=$this->site_shop_count)
        {
            $this->data['show_add_button'] = TRUE;
        }
        $this->data['form_url'] = site_url('weixin/wshop/add_shop');
        $this->data['check_mobile_uri'] = site_url('/member/index/verify_gateway?action=mobile_ver') ;
        $this->load->view('/xenon/wshop',$this->data);
    }

    /**
     * 编辑微店
     *
     *
     */

    public function edit_shop()
    {

        if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
        {
            $user_id = $this->input->get_post('user_id');
            $where = array('user_id'=>$user_id);
            $base_data = $this->input->get_post('Form');
            $expand_data = $this->input->get_post('Expand');
            $shop_data = $this->input->get_post('Shop');
            if(!empty($base_data['password']))
            {
                $ran_str = $this->Shop_model->_rand_6_char();
                $base_data['password'] = md5(md5($base_data['password'].$ran_str));
                $base_data['mix'] = $ran_str ;
            }
            $base_data = array_filter($base_data);
            $expand_data = array_filter($expand_data);
            $res = TRUE ;
            $res1 = TRUE ;
            if(!empty($base_data))
            {
                $res = $this->Shop_model->_edit_shop_user($base_data,$where) ;
            }

            if(!empty($expand_data))
            {
                $res1 = $this->Shop_model->_edit_shop_expand($expand_data,$where) ;
            }

            if(!empty($shop_data))
            {
                $shop_data['sid'] = $this->sid ;
                $info_table = $this->db->dbprefix('user_shop_info');
                $result = $this->Shop_model->get_row("$info_table.pid = $user_id");
                if(!$result){
                    $shop_data['pid'] = $user_id ;
                    $this->Shop_model->_add_shop_info($shop_data) ;
                }
                $where = array('pid'=>$user_id);
                $res1 = $this->Shop_model->_edit_shop_info($shop_data,$where) ;
            }
            $failure_url = site_url('weixin/wshop/edit_shop/'.$user_id);
            if($res&&$res1)
            {
                $this->success('操作成功',site_url('weixin/wshop/shop_list'),true);
            }

            $this->error('操作失败',$failure_url,true);

        }

        $user_id = $this->uri->segment(4);
        $user_table = $this->db->dbprefix('user');
        $this->data= $this->Shop_model->get_row("$user_table.user_id = $user_id");
        $this->data['show_add_button'] = FALSE;
        if(($this->Shop_model->get_shop_count())<=$this->site_shop_count)
        {
            $this->data['show_add_button'] = TRUE;
        }
        $this->data['user_id'] = $user_id ;
        $this->data['form_url'] = site_url('weixin/wshop/edit_shop/');
        $this->data['check_mobile_uri'] = site_url('/member/index/verify_gateway/?user_id='.$user_id.'&action=mobile_ver') ;
        $this->load->view('/xenon/wshop',$this->data);
    }

    /**
     *店铺状态
     *
     *
     */

    public function shop_status()
    {

        $post = $this->input->post();
        $data[$post['field']] = $post['val'];
        $res = $this->Shop_model->_edit_shop_info($data,array('pid'=>$post['id']));
        if($res){
            $this->success('操作成功','',true);
        }else{
            $this->error('操作失败','',true);
        }
    }

    /**
     * 删除店铺
     * @param   POST 表单数据
     * return true/false
     */

    public function delete_shop()
    {
        $id = $this->input->get('id');
        $res = $this->Shop_model->_delete_shop($id);
        if($res){
            $this->success('操作成功',site_url('weixin/wshop/shop_list'),true);
        }
        $this->error('操作失败','',true);
    }

    /**
     * 店铺编辑跳转
     * @param   mobile
     */

    public function js_shop_edit_redirect()
    {
        $user_table = $this->db->dbprefix('user');
        $mobile =  $this->input->get('mobile');
        $result = $this->Shop_model->get_row("$user_table.mobile = $mobile");
        redirect(site_url('weixin/wshop/edit_shop/'.$result['user_id']));

    }
    public function upload_avatar()
    {
        $user_id = $this->input->get_post('uid');
        $config = $this->Upload_model->upload_config('avatar');
        $this->load->library('upload', $config);
        $absolute_path = str_replace('\\', '/', getcwd()) . '/';
        if (!$this->upload->do_upload('file')) {
            $error = array('error' => $this->upload->display_errors());
            $this->error($error['error'], '', true);
        } else {
            $data = array('upload_data' => $this->upload->data());
            $message = str_replace($absolute_path, '', $data['upload_data']['full_path']);
            $file_ext = $data['upload_data']['file_ext'];
            $dir_url = '/uploads/' . $GLOBALS['sid'] . '/avatar/';
            $des_url = $dir_url . $user_id . $file_ext;
            $des = getcwd() . $des_url;
            if (copy($message, $des)) {
                if (unlink($message)) {
                    $new_url = substr($des_url, 1);
                     $where = array('user_id'=>$user_id);
                    $array['avatar'] = $new_url;
                    $this->Shop_model->_edit_shop_expand($array,$where);
                }
            }

            
           
            $this->success(URLPIC . $new_url.'?_='.time(), '', true);
        }
    }




}